package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-05-14
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {

            EasyExcel.read(file.getInputStream(), SubjectData.class,new SubjectExcelListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<EduSubject> getAllSubject() {


        List<EduSubject> eduSubjects = baseMapper.selectList(null);
        // 声明一个变量用来存储找到的根节点
        List<EduSubject> root = new ArrayList<>();
        // 创建一个map对象用来存储id和Menu对象的关系
        Map<String,EduSubject> eduSubjectMap = new HashMap<>();
        // 遍历menuList填充menuMap
        for (EduSubject eduSubject:
                eduSubjects) {
            String id = eduSubject.getId();


            eduSubjectMap.put(id,eduSubject);
        }
        // 再一次遍历menuList查找根节点、组装父子节点
        for (EduSubject eduSubject:
                eduSubjects) {
            // 获取当前menu对象的pid
            String pid = eduSubject.getParentId();
            if (pid.equals("0")){
                // 说明找到根节点了

                root.add(eduSubject);
                // 执行下一次循环
                continue;
            }

            // 如果pid不为null，说明当前节点有父节点，menuMap找到父节点
            EduSubject menuFather = eduSubjectMap.get(pid);
//            System.out.println(menuFather);
            // 将当前节点存入父节点

            menuFather.getChildren().add(eduSubject);

        }

        return root;
    }



}
